package com.jinke.api.component;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.jinke.api.common.exception.Asserts;
import com.jinke.api.security.util.AdminUserUtil;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;


@Slf4j
public class CustomBigDecimalStringConverter implements Converter<BigDecimal> {

    /*public CustomBigDecimalStringConverter(MessageSource messageSource) {
        this.messageHint = new MessageHint(messageSource);
    }*/

    @Override
    public Class<?> supportJavaTypeKey() {
        return BigDecimal.class;
    }

    /*@Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }*/

    @Override
    public BigDecimal convertToJavaData(ReadCellData cellData, ExcelContentProperty excelContentProperty,
                                        GlobalConfiguration globalConfiguration) {
        MessageHint messageHint = BeanLocator.getBean(MessageHint.class);
        CellDataTypeEnum type = cellData.getType();
        Object originalValue = null;
        switch (type) {
            case STRING:
                originalValue = cellData.getStringValue();
                break;
            case NUMBER:
                originalValue = cellData.getNumberValue();
                break;
            default:
                break;
        }
        if (originalValue == null) {
            return null; // 或者返回默认值
        }
        // 防止 type 是 字符串 捕获转换异常 处理
        try {
            return new BigDecimal(originalValue.toString());
        } catch (NumberFormatException e) {
            Object[] objects = {cellData.getRowIndex()+1, cellData.getColumnIndex()+1, originalValue, messageHint.getMessage("required.type.number", null, AdminUserUtil.getUserInfo().getUserLocale())};
            Asserts.fail(messageHint.getMessage("excel.import.format.error",  objects, AdminUserUtil.getUserInfo().getUserLocale()));
        }
        return cellData.getNumberValue();
    }

    @Override
    public WriteCellData<String> convertToExcelData(BigDecimal value, ExcelContentProperty excelContentProperty,
                                                    GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(String.valueOf(value));
    }
}
